package com.tianlang.web.member.controller;

import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.jfinal.core.ActionKey;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.tianlang.annotation.ControllerBind;
import com.tianlang.jfinal.base.BaseController;
import com.tianlang.jfinal.base.BaseRest;

/**
 * 
 * @author mcp
 *
 */
@ControllerBind(controllerKey = "/demo")
public class DemoController extends BaseController {

	private static final Logger log = Logger.getLogger(DemoController.class);

	@ActionKey("/login")
	public void login() {
		renderJson(new BaseRest());
		// render("login.html");
	}

	@ActionKey("/index")
	public void indexDefault() {
		redirect("/demo/index");
	}

	public void index() {
		log.info("DemoController==index");
		SqlPara sqlPara = Db.getSqlPara("demo.findById1", "402882f35e7f14e5015e7f1510d50000");
		Record record = Db.findFirst(sqlPara);
		log.info("findById1=" + record.getStr("userName"));
		/////////////////////////////////
		Kv conf = new Kv();
		conf.set("id", "402882f35e7f14e5015e7f1510d50000");
		sqlPara = Db.getSqlPara("demo.findById2", conf);
		record = Db.findFirst(sqlPara);
		log.info("findById2=" + record.getStr("userName"));
		///////////////////////////////
		conf = new Kv();
		conf.set("id", "402882f35e7");
		sqlPara = Db.getSqlPara("demo.findLike", conf);
		// Page<Record> page = Db.paginate(1, 20, sqlPara);
		Page<Record> page = Db.paginateByFullSql(1, 20, Db.getSql("demo.findCount"), sqlPara.getSql(),
				sqlPara.getPara());
		List<Record> records = page.getList();
		log.info("findLike=" + records.get(0).getStr("userName"));
		///////////////////////////////
		List<String> idList = Arrays.asList("402882f35e7f14e5015e7f1510d50000");
		conf = new Kv();
		conf.set("ids", idList);
		sqlPara = Db.getSqlPara("demo.findIn", conf);
		records = Db.find(sqlPara);
		log.info("findIn=" + records.get(0).getStr("userName"));
		String username = record.getStr("userName");
		String password = record.getStr("password");
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		subject.login(token);
		// setAttr("user", record);
		render("login.html");
	}
}
